import type { Env } from '../../types';
import { createErrorResponse } from '../../utils/errorHandler';

export async function handleFrontendRequest(
  request: Request,
  url: URL,
  env: Env
): Promise<Response> {
  const path = url.pathname;

  // 服务前端构建后的文件
  try {
    // 在开发环境中，前端文件由webpack-dev-server提供
    // 在生产环境中，您需要将前端文件部署到Cloudflare Pages或其他托管服务
    if (path === '/') {
      return new Response(
        `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>D1 文本分享平台</title>
  <script src="http://localhost:8080/bundle.js"></script>
</head>
<body>
  <div id="app"></div>
</body>
</html>`,
        { headers: { 'content-type': 'text/html' } }
      );
    }

    return createErrorResponse('Not found', 404);
  } catch (error) {
    console.error('Error handling frontend request:', error);
    return createErrorResponse('Internal server error', 500);
  }
}

function getContentType(path: string): string {
  if (path.endsWith('.js')) return 'application/javascript';
  if (path.endsWith('.css')) return 'text/css';
  if (path.endsWith('.html')) return 'text/html';
  return 'application/octet-stream';
}